package com.appbee.core.client.startup.impl;

import javax.inject.Provider;

import com.appbee.core.client.startup.StartupChain;
import com.appbee.core.client.startup.StartupChainBuilder;
import com.appbee.core.client.startup.StartupLink;
import com.google.gwt.user.client.ui.HasWidgets.ForIsWidget;

public class StartupChainBuilderImpl implements StartupChainBuilder
{
	private BaseChainImpl currentChain;
	private BaseChainImpl firstChain;

	@Override
	public StartupChainBuilder chain(StartupLink link)
	{
		if (currentChain == null)
		{
			currentChain = new StartupChainImpl(link);
			firstChain = currentChain;
		}
		else
		{
			StartupChainImpl newChain = new StartupChainImpl(link);
			currentChain.chain = newChain;
			currentChain = newChain;
		}
		return this;
	}

	@Override
	public StartupChainBuilder chainProvider(Provider<? extends StartupLink> linkProvider)
	{
		if (currentChain == null)
		{
			currentChain = new ProviderStartupChainImpl(linkProvider);
			firstChain = currentChain;
		}
		else
		{
			ProviderStartupChainImpl newChain = new ProviderStartupChainImpl(
					linkProvider);
			currentChain.chain = newChain;
			currentChain = newChain;
		}
		return this;
	}

	@Override
	public StartupChain getChain()
	{
		return firstChain;
	}

	public abstract class BaseChainImpl implements StartupChain
	{
		protected StartupChain chain;

	}

	public class StartupChainImpl extends BaseChainImpl
	{
		private final StartupLink link;

		public StartupChainImpl(StartupLink link)
		{
			this.link = link;
		}

		@Override
		public void start(ForIsWidget container)
		{
			if(chain==null) chain = new DummyStartupChain();
			link.start(container, chain);
		}
	}

	public class ProviderStartupChainImpl extends BaseChainImpl
	{
		private final Provider<? extends StartupLink> link;

		public ProviderStartupChainImpl(Provider<? extends StartupLink> link)
		{
			this.link = link;
		}

		@Override
		public void start(ForIsWidget container)
		{
			if (chain == null)
				chain = new DummyStartupChain();
			link.get().start(container, chain);
		}
	}
	
	public class DummyStartupChain implements StartupChain
	{

		@Override
		public void start(ForIsWidget container)
		{
		}
		
	}

}
